
package com.feib.soeasy.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.Soez5001ExcelService;
import com.feib.soeasy.service.Soez5001Service;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;
import com.feib.soeasy.util.UserUtil;

/**
 * @title (#)Soez5001ActionBean.java<br>
 * @description 異常繳款明細表 <br>
 * @author Jeff  Gu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2011/3/3 create by Jeff Gu<br>
 */
public class Soez5001ActionBean extends BaseActionBean implements ValidationErrorHandler{
    /**
     * 異常繳款明細表作業畫面(已更改)
     */
    private static final String DEFAULT_JSP = "/WEB-INF/views/soez5001/soez5001.jsp";

    /**
     * 異常繳款明細表清單畫面(列表)
     */
    private static final String PAYMENT_LIST_JSP = "/WEB-INF/views/soez5001/soez5001List.jsp";
    
    /**
     * 檔案內容
     */
    private static final String AJAX_QUERY_FEEDBACKLOG_JSP = "/WEB-INF/views/soez5001/soez5001FeedbackLog.jsp";
    

    /**
     * 業者代號查詢畫面(未確認)
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez5001/soez5001groupPopUpList.jsp";



    private Group group;
    
    /**
     * 查詢結果
     */
    private PaginatedList<Map<String, Object>> queryResult;

    /**
     * 帳單業者查詢條件
     */
    private Group qryGroup;
    
    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;
    
    private Long feedbackUid;
    
    private Long paymentPk;

    private String reason;
    
    /**
     * 繳款通路銷帳日誌
     */
    private Map<String, Object> feedbackLog;

/*
    private String groupNo;
    private String queryId;
    private String fileMessage;
    private Long groupPk;
    private Integer  caseSwitch ;
    private String queryGroupNo;
*/
    @SpringBean("groupService")
    private GroupService groupService;

    @SpringBean("soez5001Service")
    private Soez5001Service soez5001Service;

    @SpringBean("soez5001ExcelService")
    private  Soez5001ExcelService soez5001ExcelService;



    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {       
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP); 
    }

    /**
     * 查詢
     * @return
     */

    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {
            
            if (null == this.group)
                this.group = new Group();
            
            if (null == queryResult)
                queryResult = new PaginatedList<Map<String,Object>>();
            
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.group = UserUtil.getUserGroup();
            }
            
            if (StringUtils.isNotEmpty(group.getGroupNo()))
                this.group = this.groupService.findByExactGroupNo(group.getGroupNo());
            
            this.queryResult = this.soez5001Service.queryByGroup(group, queryResult);

        }
        catch (Exception e) {
            logger.error("異常狀態明細表查詢錯誤(Soez5001ActionBean.doAjaxQuery):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(PAYMENT_LIST_JSP);
    }

    public Resolution doAjaxDownloadExcelFile()
    {
        logger.debug("Enter doAjaxDownloadExcelFile mehtod.");
        try {
            if (null == this.group)
                this.group = new Group();

            
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.group = UserUtil.getUserGroup();
            }
            
            if (StringUtils.isNotEmpty(group.getGroupNo()))
                this.group = this.groupService.findByExactGroupNo(group.getGroupNo());

            String downloadFilePath = this.soez5001ExcelService.doExportXls(this.group);

            if (null == downloadFilePath)
            {
                // 查無資料
                logger.debug("查無資料");
            }

            File downloadFile = new File(downloadFilePath);
            byte[] bytes = new byte[(int)downloadFile.length()];
            logger.info("downloadFilePath {}",downloadFilePath);

            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(downloadFile)); 

            bufferedInputStream.read(bytes);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            inputStream.close();
            bufferedInputStream.close();

            String isoFileName = new String("人工核銷明細表.xls".getBytes("MS950"), "ISO8859-1");

            StreamingResolution streamingResolution = new StreamingResolution( 
                            "application/vnd.ms-excel",inputStream).setFilename(isoFileName);

            return streamingResolution;
        }
        catch (Exception e) {
            logger.error("", e);
        }
        return new ForwardResolution(DEFAULT_JSP);
    }


    /**
     * 查詢轉入的異常狀態明細資料
     * @return
     */
    public Resolution doAjaxQueryFeedbackLog()
    {
        logger.debug("Enter doAjaxQueryFeedbackLog mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.group = UserUtil.getUserGroup();
            }

            //呼叫服務查詢
            this.feedbackLog = this.soez5001Service.queryFeedbackLogByPk(this.feedbackUid, this.group);
            

        }
        catch (Exception e) {
            logger.error("上傳記錄查詢-異常狀態明細資料查詢錯誤(Soez5001ActionBean.doAjaxQueryFeedbackLog):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }
        
        return new ForwardResolution(AJAX_QUERY_FEEDBACKLOG_JSP);

    }

    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {

            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                throw new Exception("No Authority");
            }


            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("異常狀態明細資料明細資料下載-帳單業者查詢錯誤(Soez5001ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }


        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);

    }



    /**
     * 銷帳按鈕
     * @return
     */
    public Resolution doWriteOffPayment()
    {
        StringBuffer msg = new StringBuffer();
        logger.debug("Enter doWriteOffPayment mehtod.");
        try {
            this.soez5001Service.doWriteOffPayment(this.feedbackUid, this.paymentPk, this.reason);
            msg.append("銷帳成功").append("<input type='hidden' id='doWriteOffPaymentResultCode' value='1'/>");
        }
        catch (Exception e) {
            msg.append("銷帳失敗");
            logger.error("帳單人工銷帳作業錯誤(Soez5001ActionBean.doWriteOffPayment):", e);
        }
        StreamingResolution resolution = new StreamingResolution("text/html", new StringReader(msg.toString()));
        resolution.setCharacterEncoding("UTF-8");
        return resolution;

    }
    
    /**
     * 已處理按鈕
     * @return
     */
    public Resolution doSkipFeedbackLog()
    {
        StringBuffer msg = new StringBuffer();
        logger.debug("Enter doSkipFeedbackLog mehtod.");
        try {
            
            this.soez5001Service.doSkipFeedbackLog(this.feedbackUid, this.reason);
            msg.append("更新成功").append("<input type='hidden' id='doSkipFeedbackLogResultCode' value='1'/>");
            
        }
        catch (Exception e) {
            msg.append("更新失敗");
            logger.error("帳單人工銷帳作業錯誤(Soez5001ActionBean.doSkipFeedbackLog):", e);
        }
        StreamingResolution resolution = new StreamingResolution("text/html", new StringReader(msg.toString()));
        resolution.setCharacterEncoding("UTF-8");
        return resolution;

    }


    public PaginatedList<Map<String, Object>> getQueryResult() {
        return queryResult;
    }

    public void setQueryResult(PaginatedList<Map<String, Object>> queryResult) {
        this.queryResult = queryResult;
    }


   

    public Long getPaymentPk() {
        return paymentPk;
    }

    public void setPaymentPk(Long paymentPk) {
        this.paymentPk = paymentPk;
    }

    public Group getQryGroup() {
        return qryGroup;
    }

    public void setQryGroup(Group qryGroup) {
        this.qryGroup = qryGroup;
    }

    public PaginatedList<Group> getQueryGroupResult() {
        return queryGroupResult;
    }

    public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
        this.queryGroupResult = queryGroupResult;
    }

  

    /**
     * @param reason the reason to set
     */
    public void setReason(String reason) {
        this.reason = reason;
    }

    /**
     * @return the reason
     */
    public String getReason() {
        return reason;
    }

    
    /**
     * @return the group
     */
    public Group getGroup() {
        return group;
    }

    
    /**
     * @param group the group to set
     */
    public void setGroup(Group group) {
        this.group = group;
    }

    
    /**
     * @return the feedbackUid
     */
    public Long getFeedbackUid() {
        return feedbackUid;
    }

    
    /**
     * @param feedbackUid the feedbackUid to set
     */
    public void setFeedbackUid(Long feedbackUid) {
        this.feedbackUid = feedbackUid;
    }

    
    /**
     * @return the feedbackLog
     */
    public Map<String, Object> getFeedbackLog() {
        return feedbackLog;
    }

    
    /**
     * @param feedbackLog the feedbackLog to set
     */
    public void setFeedbackLog(Map<String, Object> feedbackLog) {
        this.feedbackLog = feedbackLog;
    }
}
